/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: MainPresenter.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.main.presenter;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;

import java.util.HashMap;
import java.util.List;

import io.bhex.app.R;
import io.bhex.app.account.ui.MyAssetFragment;
import io.bhex.app.base.AppUI;
import io.bhex.app.main.ui.HomeFragment;
import io.bhex.app.main.ui.KeyEventHandler;
import io.bhex.app.main.ui.MainActivity;
import io.bhex.app.market.ui.MarketFragment;
import io.bhex.app.trade.ui.ContractTradeFragment;
import io.bhex.app.trade.ui.HomeTradeFragment;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.core.SPEx;
import io.bhex.baselib.mvp.BaseCoreActivity;
import io.bhex.baselib.mvp.BasePresenter;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.baselib.utils.ToastUtils;


public class MainPresenter extends BasePresenter<MainPresenter.MainUI> {
    private Fragment curFragment;

    @Override
    public void onUIReady(BaseCoreActivity activity, MainUI ui) {
        super.onUIReady(activity, ui);
    }

    public interface MainUI extends AppUI {
        void setTabChecked(int index);

        int getTabCheckedIndex();

        View getBottomView();

        HashMap<String, Fragment> getMainFragments();
    }

    /**
     * 显示指定的Fragment
     *
     * @param fragment
     * @param bundle
     */
    public Fragment showFragment(Fragment fragment, Bundle bundle) {
        return showFragment(fragment, bundle, false);
    }

    /**
     * 显示指定的Fragment
     *
     * @param fragment
     * @param bundle
     */
    public Fragment showFragment(Fragment fragment, Bundle bundle, boolean needBundle) {
        if (curFragment != null) {
            if (curFragment.getClass().getName().equals(fragment.getClass().getName())) {
                return curFragment;
            }
        }

        FragmentManager manager = getActivity().getSupportFragmentManager();

        FragmentTransaction transaction = manager.beginTransaction();
        transaction.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

        if (curFragment != null) {
            transaction.hide(curFragment);
        }
        /*MainActivity m = (MainActivity)getActivity();
        for (int i = 0; i < m.mainFragments.size(); i++) {
            transaction.hide(m.mainFragments.)
        }*/

        if (fragment.isAdded()) {
            if (needBundle && fragment.getArguments() != null) {
                fragment.getArguments().clear();
                fragment.getArguments().putAll(bundle);
            }
            transaction.show(fragment);
        }else{
            transaction.add(R.id.main_fragment, fragment,fragment.getClass().getName());
        }

        curFragment = fragment;

        transaction.commitAllowingStateLoss();
        return curFragment;
    }



    //    /**
//     * 显示指定的Fragment
//     *
//     * @param frgClazz
//     * @param bundle
//     */
//    public Fragment showFragment(Class frgClazz, Bundle bundle) {
//        return showFragment(frgClazz, bundle, false);
//    }
//
//    /**
//     * 显示指定的Fragment
//     *
//     * @param frgClazz
//     * @param bundle
//     */
//    public Fragment showFragment(Class frgClazz, Bundle bundle, boolean needBundle) {
//
//        FragmentManager manager = getActivity().getSupportFragmentManager();
//        curFragment = manager.findFragmentByTag(frgClazz.getName());
//
//        FragmentTransaction transaction = manager.beginTransaction();
//        transaction.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
//
//        List<Fragment> fragments = manager.getFragments();
//        if (fragments!= null){
//            for (Fragment frg : fragments) {
//                if (frg != null){
//                    transaction.hide(frg);
//                }
//            }
//        }
//
//        if (curFragment == null) {
//            DebugLog.d("build fragment " + frgClazz.getSimpleName());
//            curFragment = Fragment.instantiate(getActivity(), frgClazz.getName(), bundle);
//            transaction.add(R.id.main_fragment, curFragment, frgClazz.getName());
//        } else {
//            if (needBundle && curFragment.getArguments() != null) {
//                curFragment.getArguments().clear();
//                curFragment.getArguments().putAll(bundle);
//            }
//            transaction.show(curFragment);
//        }
//
//        transaction.commitAllowingStateLoss();
//        return curFragment;
//    }

    public void handleIntent(Intent intent) {
        Bundle extras = intent.getExtras();

        if (extras == null) {
            return;
        }

        getActivity().setIntent(intent);

    }

    private boolean mExit = false;

    private Runnable exitRevert = new Runnable() {
        @Override
        public void run() {
            mExit = false;
        }
    };

    public boolean handleKeyUp(int keyCode, KeyEvent msg) {

        List<Fragment> frgs = getActivity().getSupportFragmentManager().getFragments();
        for (int i = frgs.size() - 1; i >= 0; i--) {
            if (frgs.get(i) == null || frgs.get(i).isHidden() || !(frgs.get(i) instanceof KeyEventHandler))
                continue;

            if (((KeyEventHandler) frgs.get(i)).onKeyUp(keyCode, msg)) {
                return true;
            }
        }

        if (keyCode != KeyEvent.KEYCODE_BACK) {
            return false;
        }

        if (mExit) {
            getUI().getBottomView().removeCallbacks(exitRevert);
            SPEx.set(AppData.SPKEY.APP_EXIT, 1);
            getActivity().finish();
            System.exit(0);
            return true;
        }

        mExit = true;
        ToastUtils.showShort(getActivity(), getResources().getString(R.string.string_tips_exit));

        getUI().getBottomView().postDelayed(exitRevert, AppData.EXIT_WAIT_TIMEOUT);

        return true;
    }

    public void hiddenFragment(){
        FragmentManager fm =  getActivity().getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        List<Fragment> frgs = fm.getFragments();
        DebugLog.d("MainActivity===>:","size=="+fm.getFragments().size());

        for(int i=0;i<frgs.size();i++){
            DebugLog.d("MainActivity===>:","classname=="+fm.getFragments().get(i).getClass().getName());
            if(fm.getFragments().get(i) instanceof HomeFragment){
                ft.hide(fm.getFragments().get(i));
            }

            if(fm.getFragments().get(i) instanceof MarketFragment){
               ft.hide(fm.getFragments().get(i));
            }

            if(fm.getFragments().get(i) instanceof HomeTradeFragment){
                ft.hide(fm.getFragments().get(i));
            }

            if(fm.getFragments().get(i) instanceof ContractTradeFragment){
                ft.hide(fm.getFragments().get(i));
            }

            if(fm.getFragments().get(i) instanceof MyAssetFragment){
                ft.hide(fm.getFragments().get(i));
            }
        }
        ft.commitNowAllowingStateLoss();
    }
}
